package com.bestcem.xm.ticket.grpc.client.convert;

import cn.hutool.core.collection.CollectionUtil;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.survey.grpc.v1.services.*;
import com.bestcem.xm.ticket.grpc.client.dto.survey.*;
import com.google.protobuf.Timestamp;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nullable;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 问卷项目response 转 DTO
 *
 * @author zq.ding <zq.ding@idiaoyan.com>
 * @version v1.0
 * @date 2021/8/30 10:12
 */
public class TicketBaseSurveyConvert {

    /**
     * response转ColumnDTO
     *
     * @param response 单个Column响应
     * @return 答卷数据显示列 DTO
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/8/30 14:00
     */
    public static ColumnDTO responseToColumnDTO(ColumnResponse response) {
        Column column = response.getColumn();

        ColumnDTO dto = new ColumnDTO();
        dto.setId(column.getId());
        dto.setProjectId(column.getProjectId());
        dto.setQStructIds(column.getQstructIdsList());
        dto.setGid(column.getGid());
        dto.setDispType(column.getDispType());
        dto.setRGid(column.getRgid());
        dto.setOGid(column.getOgid());
        dto.setCol(column.getCol());
        dto.setQType(column.getQtype().getNumber());
        dto.setStatus(column.getStatus().getNumber());
        dto.setCType(column.getCtype().getNumber());
        dto.setCustomAttr(column.getCustomAttr());
        dto.setSortNo(column.getSortNo());

        return dto;
    }

    /**
     * response转RespondentDTO列表
     *
     * @param response Respondent列表响应
     * @return RespondentDTO列表
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/8/30 13:56
     */
    public static List<RespondentDTO> responseToRespondentDTO(RespondentSearchResponse response) {
        List<Respondent> respondentList = response.getRespondentListList();
        // 为空则直接返回空
        if (CollectionUtil.isEmpty(respondentList)) {
            return Collections.emptyList();
        }
        List<RespondentDTO> dtoList = new ArrayList<>(respondentList.size());
        for (Respondent respondent : respondentList) {
            dtoList.add(infoToRespondentDTO(respondent));
        }
        return dtoList;
    }

    /**
     * response转QuotaCheckItemDTO
     *
     * @param response QuotaCheckItem相应
     * @return 配额检查项DTO
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/8/30 13:54
     */
    public static QuotaCheckItemDTO responseToQuotaCheckItemDTO(QuotaCheckItemResponse response) {
        QuotaCheckItem quotaCheckItem = response.getQuotaCheckItem();

        QuotaCheckItemDTO quotaCheckItemDTO = new QuotaCheckItemDTO();
        quotaCheckItemDTO.setId(quotaCheckItem.getId());
        quotaCheckItemDTO.setQuotaCondId(quotaCheckItem.getQuotaCondId());
        quotaCheckItemDTO.setProjectId(quotaCheckItem.getProjectId());
        quotaCheckItemDTO.setNum(quotaCheckItem.getNum());
        quotaCheckItemDTO.setCurCount(quotaCheckItem.getCurCount());
        // quotaCheckItemDTO.setOptionList(quotaCheckItem.getOptionListList());
        quotaCheckItemDTO.setOptionCombies(quotaCheckItem.getOptionCombiesList());

        return quotaCheckItemDTO;
    }

    /**
     * response转QuotaConditionDTO
     *
     * @param response QuotaCondition响应
     * @return 配额条件DTO
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/8/30 13:54
     */
    public static QuotaConditionDTO responseToQuotaConditionDTO(QuotaConditionResponse response) {
        QuotaCondition quotaCondition = response.getQuotaCondition();

        QuotaConditionDTO quotaConditionDTO = new QuotaConditionDTO();
        quotaConditionDTO.setId(quotaCondition.getId());
        quotaConditionDTO.setName(quotaCondition.getName());
        quotaConditionDTO.setProjectId(quotaCondition.getProjectId());
        quotaConditionDTO.setQuotaId(quotaCondition.getQuotaId());
        // quotaConditionDTO.setQGidList(quotaCondition.getQgidListList());
        // quotaConditionDTO.setQuotaCheckitemList(quotaCondition.getQuotaCheckitemListList());
        quotaConditionDTO.setCheckPoints(quotaCondition.getCheckpoints());

        return quotaConditionDTO;
    }

    /**
     * grpc转DTO
     *
     * @param respondent grpc生成的
     * @return RespondentDTO DTO对象
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/8/30 14:02
     */
    public static RespondentDTO infoToRespondentDTO(Respondent respondent) {
        RespondentDTO respondentDTO = new RespondentDTO();

        respondentDTO.setId(respondent.getId());
        respondentDTO.setProjectId(respondent.getProjectId());
        respondentDTO.setDataStatus(respondent.getDataStatus().getNumber());
        respondentDTO.setStatus(respondent.getStatus().getNumber());
        respondentDTO.setPreDiscardStatus(respondent.getPreDiscardStatus());
        respondentDTO.setSeq(respondent.getSeq());
        respondentDTO.setParsed(respondent.getParsed());
        respondentDTO.setVersion(respondent.getVersion());
        respondentDTO.setSource(respondent.getSource().getNumber());
        respondentDTO.setGroupId(respondent.getGroupId());
        respondentDTO.setGroupCode(respondent.getGroupCode());
        respondentDTO.setPersonId(respondent.getPersonId());
        respondentDTO.setUserAgent(respondent.getUserAgent());
        respondentDTO.setClientType(respondent.getClientType().getNumber());
        respondentDTO.setIp(respondent.getIp());

        respondentDTO.setBeginTime(googleTimestampToLocalDateTime(respondent.getBeginTime()));
        respondentDTO.setFinishTime(googleTimestampToLocalDateTime(respondent.getFinishTime()));
        respondentDTO.setCreatedDt(googleTimestampToLocalDateTime(respondent.getCreatedDt()));

        respondentDTO.setRspdDataId(respondent.getRspdDataId());
        respondentDTO.setRspdWeixinId(respondent.getRspdWeixinId());
        respondentDTO.setRspdLocationId(respondent.getRspdLocationId());
        respondentDTO.setRspdExtraId(respondent.getRspdExtraId());
        respondentDTO.setRspdAttachmentId(respondent.getRspdAttachmentId());
        respondentDTO.setExtSeq(respondent.getExtSeq());
        respondentDTO.setSubmitSeq(respondent.getSubmitSeq());
        respondentDTO.setIpCountry(respondent.getIpCountry());
        respondentDTO.setIpProvince(respondent.getIpProvince());
        respondentDTO.setIpCity(respondent.getIpCity());
        respondentDTO.setRemark(respondent.getRemark());
        respondentDTO.setMemberId(respondent.getMemberId());
        respondentDTO.setCurrentLang(respondent.getCurrentLang());
        respondentDTO.setDeliverId(respondent.getDeliverId());
        respondentDTO.setDeliverGroupId(respondent.getDeliverGroupId());
        respondentDTO.setAgainDeliverRecordId(respondent.getAgainDeliverRecordId());
        respondentDTO.setQuotaCheckitemList(respondent.getQuotaCheckitemList());

        respondentDTO.setExcelParsed(respondent.getExcelParsed());
        respondentDTO.setSurveyGids(respondent.getSurveyGidsList());
        respondentDTO.setWxInfo(respondent.getWxInfo());
        respondentDTO.setDedCode(respondent.getDedCode());
        respondentDTO.setIdySid(respondent.getIdySid());
        respondentDTO.setScore(respondent.getScore());

        return respondentDTO;
    }

    private static LocalDateTime googleTimestampToLocalDateTime(Timestamp timestamp) {
        if (timestamp == null || timestamp.getSeconds() < 0) {
            return null;
        }
        Date date = new Date(timestamp.getSeconds() * 1000);
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    /**
     * response to List<ColumnDTO>
     *
     * @param response 根据 survey_id获取 问卷列 的 response
     * @return 答卷数据显示列DTO 集合
     * @author <yuming.pan@idiaoyan.com>
     * @date 15:05 2021/8/31
     */
    public static List<ColumnDTO> responseToColumnDTOList(GetColumnsBySurveyIdResponse response) {
        List<Column> columnsList = response.getColumnsList();
        List<ColumnDTO> columnDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(columnsList)) {
            columnsList.forEach(column -> {
                if (Objects.nonNull(column)) {
                    ColumnDTO columnDTO = infoToColumnDTO(column);
                    columnDTOList.add(columnDTO);
                }
            });
        }
        return columnDTOList;
    }

    /**
     * Column to ColumnDTO
     *
     * @param column proto生成的Column
     * @return 答卷数据显示列DTO
     * @author <yuming.pan@idiaoyan.com>
     * @date 15:06 2021/8/31
     */
    private static ColumnDTO infoToColumnDTO(Column column) {
        if (Objects.isNull(column)) {
            return null;
        }
        ColumnDTO columnDTO = new ColumnDTO();
        columnDTO.setId(column.getId());
        columnDTO.setProjectId(column.getProjectId());
        columnDTO.setQStructIds(column.getQstructIdsList());
        columnDTO.setGid(column.getGid());
        columnDTO.setDispType(column.getDispType());
        columnDTO.setRGid(column.getRgid());
        columnDTO.setOGid(column.getOgid());
        columnDTO.setCol(column.getCol());
        columnDTO.setQType(column.getQtypeValue());
        columnDTO.setStatus(column.getStatusValue());
        columnDTO.setCType(column.getCtypeValue());
        columnDTO.setCustomAttr(column.getCustomAttr());
        columnDTO.setSortNo(column.getSortNo());
        return columnDTO;
    }

    /**
     * GetRespondentBySeqResponse转RespondentBySeqDTO
     *
     * @param response 根据 seq 获取 Respondent 的response
     * @return dto
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/8/31 15:56
     */
    public static RespondentDTO responseToRespondentDTO(GetRespondentBySeqResponse response) {

        RespondentDTO respondentDTO = infoToRespondentDTO(response.getRespondent());
        respondentDTO.setAnswers(response.getAnswer());
        RespondentExtraDTO respondentExtraDTO = new RespondentExtraDTO();
        RespondentExtra extra = response.getExtra();
        respondentExtraDTO.setId(extra.getId());
        respondentExtraDTO.setProjectId(extra.getProjectId());
        respondentExtraDTO.setRid(extra.getRid());
        respondentExtraDTO.setSimilarStatus(extra.getSimilarStatus().getNumber());
        respondentExtraDTO.setBrandInfo(extra.getBrandInfo());
        respondentExtraDTO.setModelInfo(extra.getModelInfo());

        respondentDTO.setExtra(respondentExtraDTO);

        MemberNodeDTO memberNodeDTO = new MemberNodeDTO();
        MemberNode memberNode = response.getMember();
        memberNodeDTO.setName(memberNode.getName());
        memberNodeDTO.setGender(memberNode.getGender());
        memberNodeDTO.setPhone(memberNode.getPhone());
        memberNodeDTO.setEmail(memberNode.getEmail());
        respondentDTO.setMember(memberNodeDTO);

        respondentDTO.setMemberTags(response.getMemberTagsList());
        respondentDTO.setExtParams(response.getExtParam());
        return respondentDTO;
    }

    /**
     * 将response中的一些额外参数（即之前FilledRespondentInfoDTO有但RespondentDTO没有的参数），设置到respondentDTO中
     *
     * @param respondentDTO respondentDTO
     * @param response      获取添加额外参数数据的 Respondent 的response
     * @return respondentDTO
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 18:19 2021/9/1
     */
    public static RespondentDTO responseToRespondentDTO(RespondentDTO respondentDTO, GetFilledRespondentInfoResponse response) {
        respondentDTO.setCostTime(response.getCostTime());
        respondentDTO.setRespondentStatus(response.getRespondentStatusValue());
        respondentDTO.setQuotaCheckItems(response.getQuotaCheckItemsList());
        if (Objects.nonNull(response.getCreateTime())) {
            respondentDTO.setCreateTime(DateUtil.getLocalDateTime(response.getCreateTime()));
        }
        if (Objects.nonNull(response.getEndTime())) {
            respondentDTO.setEndTime(DateUtil.getLocalDateTime(response.getEndTime()));
        }
        if (Objects.nonNull(response.getStartTime())) {
            respondentDTO.setStartTime(DateUtil.getLocalDateTime(response.getStartTime()));
        }
        respondentDTO.setAttachmentId(response.getAttachmentId());
        respondentDTO.setBrowser(response.getBrowser());
        respondentDTO.setComment(response.getComment());
        respondentDTO.setDataId(response.getDataId());
        respondentDTO.setDeliverChannel(response.getDeliverChannel());
        respondentDTO.setDeliverCode(response.getDeliverCode());
        respondentDTO.setDeliverSource(response.getDeliverSource());
        respondentDTO.setExtraId(response.getExtraId());
        respondentDTO.setGroup(response.getGroup());
        respondentDTO.setIdySurveyUnionId(response.getIdySurveyUnionId());
        respondentDTO.setLocationId(response.getLocationId());
        respondentDTO.setMemberInfo(response.getMemberInfo());
        respondentDTO.setMemberName(response.getMemberName());
        respondentDTO.setOs(response.getOs());
        respondentDTO.setUserId(response.getUserId());
        respondentDTO.setWeixinId(response.getWeixinId());
        respondentDTO.setWxUserInfo(response.getWxUserInfo());
        return respondentDTO;
    }

    /**
     * response to ContactNodeDTO
     *
     * @param response GGetContactBySeq的响应
     * @return 联系人信息
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 18:11 2021/9/18
     */
    public static ContactNodeDTO responseToContactNodeDTO(GetContactBySeqResponse response) {
        ContactNode contact = response.getContact();
        ContactNodeDTO contactNodeDTO = new ContactNodeDTO();
        contactNodeDTO.setCode(contact.getCode());
        contactNodeDTO.setMessage(contact.getMessage());
        contactNodeDTO.setPhone(contact.getPhone());
        contactNodeDTO.setEmail(contact.getEmail());
        return contactNodeDTO;
    }


    /**
     * info to RespondentDataDTO
     *
     * @param info proto RespondentData 实体
     * @return 答卷答案信息
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/11/25 20:09
     */
    @Nullable
    public static RespondentDataDTO infoToRespondentDataDTO(RespondentData info) {
        if (Objects.isNull(info)) {
            return null;
        }
        RespondentDataDTO dto = new RespondentDataDTO();
        dto.setId(info.getId());
        dto.setProjectId(info.getProjectId());
        dto.setRid(info.getRid());
        dto.setAnswers(info.getAnswers());
        dto.setSeq(info.getSeq());
        dto.setCustomAnswers(info.getCustomAnswers());
        dto.setQuestionList(info.getQuestionList());
        dto.setReportUrl(info.getReportUrl());
        return dto;
    }
}
